package com.orangelife.mobile.main.view;

import android.animation.Keyframe;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.sp.OtherSp;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.MoneyUtil;
import com.curry.android.util.StringUtil;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.main.biz.MainHttpBz;

import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 红包
 * Created by 绯若虚无 on 2016/1/5.
 */
public class RedEnvelopeActivity extends Activity {
    @Bind(R.id.tvGet)
    TextView tvGet;
    @Bind(R.id.ivClose)
    ImageView ivClose;
    @Bind(R.id.rlMain)
    RelativeLayout rlMain;
    @Bind(R.id.tvRank)
    TextView tvRank;
    @Bind(R.id.tvRank2)
    TextView tvRank2;
    //快抢抢看
    @Bind(R.id.tvInfo1)
    TextView tvInfo1;
    //被抢走了
    @Bind(R.id.tvInfo2)
    TextView tvInfo2;
    //恭喜您
    @Bind(R.id.tvInfo3)
    TextView tvInfo3;
    //正在往红包塞钱
    @Bind(R.id.tvInfo4)
    TextView tvInfo4;
    @Bind(R.id.ivCoinBackground)
    ImageView ivCoinBackground;
    /** 是否已经打开红包 */
    private boolean hasOpenEnvelope = false;
    /** 是否在该小区已认证 */
    private boolean hasCert = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_red_envelope);
        ButterKnife.bind(this);
        getIntentInfo();
        setFinishOnTouchOutside(false);
    }

    private void startRotate() {
        tvGet.setVisibility(View.GONE);
        tvInfo1.setVisibility(View.GONE);
        ivCoinBackground.setBackgroundResource(R.drawable.ic_red_envelope_coin);
        Rotate3dAnimation rotation = new Rotate3dAnimation(
                0,
                360,
                ivCoinBackground.getWidth() / 2,
                ivCoinBackground.getHeight() / 2, 1, true);
        rotation.setDuration(1000);
        rotation.setFillAfter(true);
        rotation.setRepeatCount(-1);
        rotation.setInterpolator(new LinearInterpolator());
        ivCoinBackground.startAnimation(rotation);
    }

    private void stopRotate() {
        ivCoinBackground.setBackgroundResource(R.drawable.ic_red_envelope_coin_b);
        ivCoinBackground.clearAnimation();
    }

    private void getIntentInfo() {
        boolean isCountDown = getIntent().getBooleanExtra("isCountDown", true);
        if (isCountDown) {
            hasOpenEnvelope = true;
            showWait();
        }
    }

    /** 还未开始 */
    private void showWait() {
        tvInfo1.setVisibility(View.GONE);
        tvGet.setVisibility(View.GONE);

        tvInfo4.setVisibility(View.VISIBLE);
        tvRank2.setVisibility(View.VISIBLE);
    }

    /** 抢到了 */
    private void showWin(String money) {
        tvInfo1.setVisibility(View.GONE);
        tvGet.setVisibility(View.GONE);
        ivCoinBackground.setVisibility(View.GONE);

        rlMain.setBackgroundResource(R.drawable.ic_red_envelope_win);

        tvInfo3.setVisibility(View.VISIBLE);
        money = MoneyUtil.handleMoney(money);
        tvInfo3.setText(Html.fromHtml("<font color=#ffffff>恭喜您获得了</font><br><font color=#f9e83f><big>" + money + "</big></font><font color=#ffffff>元！</font>"));
        tvRank.setVisibility(View.VISIBLE);
    }

    /** 没抢到 */
    private void showLost() {
        tvInfo1.setVisibility(View.GONE);
        tvGet.setVisibility(View.GONE);
        ivCoinBackground.setVisibility(View.GONE);

        rlMain.setBackgroundResource(R.drawable.ic_red_envelope_lost);

        tvInfo2.setVisibility(View.VISIBLE);
    }

    private void saveRedEnvelopeID(String redenvID) {
        if (!StringUtil.isBlank(redenvID)) {
            OtherSp.setRedEnvelopeID(redenvID);
        }
    }

    /** 请求红包 */
    private void requestRedEnvelope() {
        startRotate();
        MainHttpBz.getRedEnvelopeMoney(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                stopRotate();
                shakeAnimation();
                if (OrangeErrorHandler.getInstance().isSuccess(response)) {
                    //通过接口，将红包关闭事件传递给Main，0就是没抢到
                    ArrayList<String> list = OrangeDataHandler.getValueListWithEntity(response, "getMoney", "redenvID");
                    if (list != null && list.size() == 2) {
                        hasOpenEnvelope = true;
                        String money = list.get(0);
                        String redenvID = list.get(1);
                        if ("0".equals(money)) {
                            showLost();
                        } else {
                            showWin(money);
                            saveRedEnvelopeID(redenvID);
                        }
                    } else {
//                        ToastHelper.getInstance()._toast("请求失败...");
                        showLost();
                    }
                } else if (errCode == 101001) {/*用户在该小区无认证房屋*/
                    hasCert = false;
                    onClose();
                } else {
                    showLost();
                }
//                showWin("1000");
                //else hasOpenEnvelope=false;
            }
        });
    }


    @OnClick({R.id.tvGet, R.id.ivClose, R.id.tvRank, R.id.tvRank2})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvGet:
                requestRedEnvelope();
                break;
            case R.id.ivClose:
                onClose();
                break;
            case R.id.tvRank2:
            case R.id.tvRank:
                jumpToRank();
                break;
        }
    }

    private void jumpToRank() {
        IntentHelper.getInstances().getIntent(this, RedEnvelopeRankActivity.class);
        //                startRotate();
//        String redEnvelopeID = .getInstance().getRedEnvelopeID();
//        String url = CurryApplication.getInstance().getServerURL() + "/orangelife_web/views/share/leaderboard.html?redenvID=" + redEnvelopeID + "&au_userID=&au_commID=&random=" + System.currentTimeMillis();
//        LogE.E(url);
//        JumpUtil.jumpActivity(this, url);
    }

    private void onClose() {
        Intent intent = new Intent();
        intent.putExtra("hasOpenEnvelope", hasOpenEnvelope);
        intent.putExtra("hasCert", hasCert);
        setResult(0, intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        onClose();
    }

    private void shakeAnimation() {
        ObjectAnimator animator = tada(rlMain);
        animator.setRepeatCount(0);
        animator.start();
    }

    public static ObjectAnimator tada(View view) {
        return tada(view, 1f);
    }

    public static ObjectAnimator tada(View view, float shakeFactor) {

        PropertyValuesHolder pvhScaleX = PropertyValuesHolder.ofKeyframe(View.SCALE_X,
                Keyframe.ofFloat(0f, 1f),
                Keyframe.ofFloat(.1f, .9f),
                Keyframe.ofFloat(.2f, .9f),
                Keyframe.ofFloat(.3f, 1.1f),
                Keyframe.ofFloat(.4f, 1.1f),
                Keyframe.ofFloat(.5f, 1.1f),
                Keyframe.ofFloat(.6f, 1.1f),
                Keyframe.ofFloat(.7f, 1.1f),
                Keyframe.ofFloat(.8f, 1.1f),
                Keyframe.ofFloat(.9f, 1.1f),
                Keyframe.ofFloat(1f, 1f)
        );

        PropertyValuesHolder pvhScaleY = PropertyValuesHolder.ofKeyframe(View.SCALE_Y,
                Keyframe.ofFloat(0f, 1f),
                Keyframe.ofFloat(.1f, .9f),
                Keyframe.ofFloat(.2f, .9f),
                Keyframe.ofFloat(.3f, 1.1f),
                Keyframe.ofFloat(.4f, 1.1f),
                Keyframe.ofFloat(.5f, 1.1f),
                Keyframe.ofFloat(.6f, 1.1f),
                Keyframe.ofFloat(.7f, 1.1f),
                Keyframe.ofFloat(.8f, 1.1f),
                Keyframe.ofFloat(.9f, 1.1f),
                Keyframe.ofFloat(1f, 1f)
        );

        PropertyValuesHolder pvhRotate = PropertyValuesHolder.ofKeyframe(View.ROTATION,
                Keyframe.ofFloat(0f, 0f),
                Keyframe.ofFloat(.1f, -3f * shakeFactor),
                Keyframe.ofFloat(.2f, -3f * shakeFactor),
                Keyframe.ofFloat(.3f, 3f * shakeFactor),
                Keyframe.ofFloat(.4f, -3f * shakeFactor),
                Keyframe.ofFloat(.5f, 3f * shakeFactor),
                Keyframe.ofFloat(.6f, -3f * shakeFactor),
                Keyframe.ofFloat(.7f, 3f * shakeFactor),
                Keyframe.ofFloat(.8f, -3f * shakeFactor),
                Keyframe.ofFloat(.9f, 3f * shakeFactor),
                Keyframe.ofFloat(1f, 0)
        );

        return ObjectAnimator.ofPropertyValuesHolder(view, pvhScaleX, pvhScaleY, pvhRotate).
                setDuration(1000);
    }

    public static ObjectAnimator nope(View view) {
        int delta = view.getResources().getDimensionPixelOffset(R.dimen.diver_height_large);

        PropertyValuesHolder pvhTranslateX = PropertyValuesHolder.ofKeyframe(View.TRANSLATION_X,
                Keyframe.ofFloat(0f, 0),
                Keyframe.ofFloat(.10f, -delta),
                Keyframe.ofFloat(.26f, delta),
                Keyframe.ofFloat(.42f, -delta),
                Keyframe.ofFloat(.58f, delta),
                Keyframe.ofFloat(.74f, -delta),
                Keyframe.ofFloat(.90f, delta),
                Keyframe.ofFloat(1f, 0f)
        );

        return ObjectAnimator.ofPropertyValuesHolder(view, pvhTranslateX).
                setDuration(500);
    }
}
